package com.hp.sso.qq.api.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import com.alibaba.fastjson.JSONObject;
import com.hp.sso.bean.QQUserInfo;
import com.hp.sso.qq.api.QQAPIInterface;

/**
 * <p>Description:QQAPI实现类</p>
 * @author 胡鹏
 * @date 2018年10月31日
 */
public class QQAPIInterfaceImpl extends AbstractOAuth2ApiBinding implements QQAPIInterface {
	
	//获取授权码
    private static final String QQ_URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";
    
    //获取用户信息
    private static final String QQ_URL_GET_USER_INFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";
    
    /**
     * appId 配置文件读取
     */
    private String appId;
    /**
     * openId 请求QQ_URL_GET_OPENID返回
     */
    private String openId;
	
    
	public QQAPIInterfaceImpl(String accessToken, String appId) {
		
		//access_token作为查询参数来携带
		super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
		
		this.appId = appId;
		
		String url = String.format(QQ_URL_GET_OPENID, accessToken);
        String result = getRestTemplate().getForObject(url, String.class);

        this.openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
		
	}
    
	@Override
	public QQUserInfo getUserInfo() {
		String url = String.format(QQ_URL_GET_USER_INFO, appId, openId);
        String result = getRestTemplate().getForObject(url, String.class);

        QQUserInfo userInfo = JSONObject.parseObject(result, QQUserInfo.class);
        userInfo.setOpenId(openId);
        return userInfo;
	}

}
